package com.chaopei.tools;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @Author Corday 天涯
 * @Date 2022/3/23 11:43
 * Java连接mysql
 */
public class DBTools {
    //    声明用户名与密码,驱动及数据库地址
    private static final String username = "root";
    private static final String passwrod = "1234";
    private static final String driver = "com.mysql.jdbc.Driver";
    private static final String url = "jdbc:mysql://localhost:3306/mydb?useSSL=false&characterEncoding=utf8";
    //拿到数据库连接对象,用于管理mysql数据库的首要工具
    //方便在其它地方重复调用
    public static Connection getConn() {
        //声明连接对象
        Connection connection = null;
//        加载mysql驱动,同时连接mysql服务器
        try {
            Class.forName(driver);
            //System.out.println("加载成功!");
//           生成数据库连接对象
            connection= DriverManager.getConnection(url,username,passwrod);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }//conn
// 关闭数据库连接对象
   public  static  void closeConn(Connection connection){
        if(connection!=null){
            try {
                connection.close();
//                System.out.println("已正常关闭!");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
   }

    ////检测一下
    public static void main(String[] args) {
       //Connection temp=getConn();
       //closeConn(temp);
    }
}
